<template>
  <!-- 危急值上报 -->
  <div id="reportCriticalValueDetail">
    <vxe-modal v-model="detailModalShow" id="myModalResult" width="80%" height="80%" min-width="460" min-height="320" destroy-on-close show-zoom transfer :z-index="1004">
      <template #title>
        <span>危急值上报</span>
      </template>

      <template #default>
        <el-descriptions :column="4" labelClassName="description-label" contentClassName="description-content" border class="margin-bottom-sm">
          <el-descriptions-item>
            <template #label>
              <span>姓名</span>
            </template>
            <span>{{ mainInfo.patNa }}</span>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <span>病历号</span>
            </template>
            <span>{{ mainInfo.patNo }}</span>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <span>性别</span>
            </template>
            <span> {{ mainInfo.sex === '1' ? '男' : mainInfo.sex === '2' ? '女' : '未知' }}</span>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <span>年龄</span>
            </template>
            <span>{{ mainInfo.age }}</span>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <span>病人类型</span>
            </template>
            <div v-for="(item, index) in patTypeList" :key="index">
              <span v-if="item.code === mainInfo.patType">{{ item.name }}</span>
            </div>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <span>科室</span>
            </template>
            <span>{{ mainInfo.reqDeptNa }}</span>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <span>样本类型</span>
            </template>
            <span>{{ mainInfo.sampleTypeNa }}</span>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <span>报告单元</span>
            </template>
            <span>{{ mainInfo.rptGroupNa }}</span>
          </el-descriptions-item>
        </el-descriptions>

        <div class="tableForm">
          <div class="tableBody">
            <vxe-table ref="wlResultListTable" border height="100%" :data="wlResultList" :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{
                isArrow: true
              }" :radio-config="{ highlight: true }" :edit-config="{ trigger: 'click', mode: 'cell' }" resizable show-overflow>
              <vxe-column type="checkbox" width="30" align="left"></vxe-column>
              <vxe-column type="seq" title="序号" width="30" align="left"></vxe-column>
              <vxe-column field="alarmType" title="危急值" width="85" align="left">
                <template #default="{ row }">
                  <span v-if="row.criticalItemType===3">细菌危急值</span>
                  <span v-if="row.criticalItemType===4">药敏危急值</span>
                </template>
              </vxe-column>
              <vxe-column field="isReport" width="90" title="是否通报" align="left">
                <template #default="{ row }">
                  <vxe-switch v-model="row.isReport" size="mini" open-label="是" close-label="否" open-value="1" close-value="0"></vxe-switch>
                </template>
              </vxe-column>
              <vxe-column field="germNa" title="鉴定结果" width="150" align="left"></vxe-column>
              <vxe-column field="testResult" title="结果描述" width="150" align="left" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #edit="{ row }">
                  <vxe-input v-model="row.testResult" placeholder="结果描述" />
                </template>
              </vxe-column>
              <vxe-column field="resiPhenNa" title="耐药表型" width="150" align="left"></vxe-column>
              <vxe-column field="urinColoCount" title="尿细菌计数" width="150" align="left"></vxe-column>
              <vxe-column field="infeSiteNa" title="感染部位" width="150" align="left"></vxe-column>
              <vxe-column field="alarmText" title="危急值信息" min-width="150" show-overflow>
                <template #default="{ row }">
                  <template v-if='row.criticalItemType==3'>
                    {{row.alarmText}}
                  </template>
                  <template v-if='row.criticalItemType==4'>
                    {{row.drugAlarmText}}
                  </template>
                </template>
              </vxe-column>
              <vxe-column field="measure" title="处理措施" align="left" width="150" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #default="{ row }">
                  <span>{{ measureList && measureList.length > 0 && row.measure ? measureList.filter((p) => p.code === row.measure)[0].name : '' }}</span>
                </template>
                <template #edit="{ row }">
                  <vxe-select v-model="row.measure" placeholder="" clearable transfer class-name="width-100-percentage">
                    <vxe-option v-for="(item, index) in measureList" :key="index" :label="item.name" :value="item.code"></vxe-option>
                  </vxe-select>
                </template>
              </vxe-column>
            </vxe-table>
          </div>

          <div class="formBody form-panel">
            <el-form :model="detailForm" label-width="120px" style="margin-top: 10px">
              <el-row :gutter="20">
                <el-col :span="10">
                  <el-form-item label="被 通 知 人">
                    <VxePulldownSelection class="width-100-percentage" ref="employeeSelectRef" :url="'/api/sys/hisEmployee/finAllHisEmployeeList'" @confirmClick="SelectRowClick1" :tableColumn="[
                        { title: '编号', field: 'code' },
                        { title: '名称', field: 'name' }
                      ]" :aimKeys="[
                        { formKey: 'code', rowKey: 'code' },
                        { formKey: 'name', rowKey: 'name' }
                      ]" :displayTexts="['name']" :displayTextObj="detailForm.notifyPerson" />
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item label="上 报 人 员">
                    <VxePulldownSelection class="width-100-percentage" ref="employeeSelectRef" :url="'/api/user/getUserInfoList'" @confirmClick="SelectRowClick" :tableColumn="[
                        { title: '编号', field: 'username' },
                        { title: '名称', field: 'realname' }
                      ]" :aimKeys="[
                        { formKey: 'username', rowKey: 'username' },
                        { formKey: 'realname', rowKey: 'realname' }
                      ]" :displayTexts="['realname']" :displayTextObj="detailForm.reportPerson" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="10">
                  <el-form-item label="申 请 单 号">
                    <el-input v-model="detailForm.requestNo" placeholder="请输入申请单号" disabled> </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item label="备 注">
                    <el-input v-model="detailForm.remark" placeholder="请输入备 注"> </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="10">
                  <el-form-item label="上 报 时 间">
                    <el-date-picker style="width: 100%" :disabled="!allowEditRptTime" v-model="detailForm.reportTime" type="datetime" placeholder="选择上报时间" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item label="是否复查">
                    <vxe-checkbox v-model="detailForm.isReTest" :checked-value="1" :unchecked-value="0" content="是否复查"></vxe-checkbox>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="通知方式">
                    <vxe-select v-model="detailForm.notificationType" placeholder="" clearable transfer class-name="width-100-percentage">
                      <vxe-option v-for="(item, index) in criNotoficationTypeList" :key="index" :label="item.name" :value="item.code"></vxe-option>
                    </vxe-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <div style="width: 100%; text-align: center">
                <el-button type="primary" @click="save" :disabled='resultIsDisabled()'>上报</el-button>
                <el-button @click="detailModalShow = false">取消</el-button>
              </div>
            </el-form>
          </div>
        </div>
      </template>
    </vxe-modal>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, defineExpose, getCurrentInstance } from 'vue';
import { IsEmpty, sortByField, formatDateTime } from '@/utils/common';
import SelectDataList from '@/components/SelectDataList.vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { getOptionValueByCodeGlobalOption, getOptionValueByCodeRptGroupOption } from '@/utils/SysOptionsHelper';
import VxePulldownSelection from '@/components/VxePulldownSelection.vue'; //引入下拉组件
import { AppStore } from '@/stores/store';
let store = AppStore();

let { proxy }: any = getCurrentInstance();

let detailModalShow = ref(false); //危急值具体上报弹框
let mainInfo = reactive({}); //主记录病人信息
let wlResultList = reactive([]); //结果
let measureList = reactive([]); //字典表:处置措施
let criNotoficationTypeList = reactive([]); //字典表:危急值提醒方式
let patTypeList = reactive([]); //字典表:病人类型
let resultflags: any = reactive([]); //字典表：结果标志 resultflag
let detailForm = reactive({
  notifyPerson: '', //被通知人
  reqDoctorNa: '', //被通知人(申请人)
  reportPerson: store.userInfo.username, //上报人员编号
  testDoctorNa: store.userInfo.realname, //上报人员名称(检验人)
  requestNo: '', //申请单号
  remark: '', //备注
  reportTime: formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss'),
  itemNo: '',
  patNo: '',
  isReTest: 1,
  notificationType: '001'
});

let allowEditRptTime = ref(false); /**允许编辑上报时间 */

defineExpose({
  criticaReportData
});
function criticaReportData(mainInfoData: any) {
  mainInfo = mainInfoData;
  detailModalShow.value = true;
  detailForm.notifyPerson = '';
  detailForm.reqDoctorNa = '';
  detailForm.remark = '';
  detailForm.reportTime = formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss');
  detailForm.requestNo = mainInfoData.reqNo;
  /**系统选项控制 */
  //getOptionValueByCodeGlobalOption

  const a = getOptionValueByCodeGlobalOption('wjzsbmrjsrwsjys'); /**危急值上报默认接收人为送检医生 */
  if (a && (a === '1' || a === 1)) {
    if (!IsEmpty(mainInfoData.reqDoctor)) {
      detailForm.notifyPerson = mainInfoData.reqDoctor;
      detailForm.reqDoctorNa = mainInfoData.reqDoctorNa;
    }
  }

  const b = getOptionValueByCodeGlobalOption('wjzsbmrsbry'); /**危急值上报默认上报人员 */
  if (b && (b === '0' || b === 0)) {
    if (!IsEmpty(mainInfoData.testDoctor)) {
      detailForm.reportPerson = mainInfoData.testDoctor;
      detailForm.testDoctorNa = mainInfoData.testDoctorNa;
    }
  }
  if (b && (b === '1' || b === 1)) {
    if (!IsEmpty(mainInfoData.chkDoctor)) {
      detailForm.reportPerson = mainInfoData.chkDoctor;
    }
  }

  const c = getOptionValueByCodeGlobalOption('yxxgwjzsbsj'); /**允许修改危急值上报时间 */
  if (a && (c === '1' || c === 1)) {
    allowEditRptTime.value = true;
  }

  getDictMeasureList();
  getDictCriNotificationTypeList();
  getDictPatTypeList();
  getAlarmResultData();
  getDictDetailList();
}

//获取是危急值的检验结果
function getAlarmResultData(callback) {
  wlResultList.length = 0;
  const url = '/api/bac/bac-test-result/getAlarmResult';
  proxy.$http
    .get(url, { params: { rptGroup: mainInfo.rptGroup, sampleda: mainInfo.sampleda, sampleNo: mainInfo.sampleNo } })
    .then((res: any) => {
      //wlResultList.push(...res.data);
      //遍历res.data元素写入wlResultList
      res.data.forEach((item, idx) => {
        if (item.isAlarm == '1' && IsEmpty(item.cultical3Id)) {
          const iteminfo = {};
          Object.assign(iteminfo, item);
          iteminfo.criticalItemType = 3;
          wlResultList.push(iteminfo);
        }
        if (item.isDrugAlarm == '1' && IsEmpty(item.cultical4Id)) {
          const drugiteminfo = {};
          Object.assign(drugiteminfo, item);
          drugiteminfo.criticalItemType = 4;
          wlResultList.push(drugiteminfo);
        }
      });
      // 获取表格实例
      proxy.$nextTick(() => {
        if (wlResultList.length > 0) {
          for (const item of wlResultList) {
            item.isReport = '1';
          }
        }
        const $table = proxy.$refs.wlResultListTable as any;
        if ($table) {
          $table.setAllCheckboxRow(true); //全部勾选
        }
      });
      if (callback) {
        callback();
      }
    })
    .catch((err) => {
      VxeMessage(err.data.error.message, VxeNotifyType.error);
    });
}
//上报
function save() {
  const $table = proxy.$refs.wlResultListTable as any;
  const selectRows = $table.getCheckboxRecords();
  if (selectRows.length <= 0) {
    proxy.$XModal.message({ content: '还未选择需要上报的数据', status: 'warning' });
    return;
  }
  const saveData = [];
  const logData = [];
  const tzfs = criNotoficationTypeList.filter(p => p.code == detailForm.notificationType).map(p => p.name).join(',');
  selectRows.forEach((item, idx) => {
    const data = {};
    data.rptGroup = item.rptGroup;
    data.sampleda = item.sampleda;
    data.sampleNo = item.sampleNo;
    data.resultId = item.id;
    data.isReport = IsEmpty(item.isReport) ? 0 : item.isReport;
    data.measure = IsEmpty(item.measure) ? null : item.measure;
    data.notifyPerson = IsEmpty(detailForm.notifyPerson) ? null : detailForm.notifyPerson;
    data.notifyPersonNa = IsEmpty(detailForm.reqDoctorNa) ? null : detailForm.reqDoctorNa;
    data.reportPerson = IsEmpty(detailForm.reportPerson) ? null : detailForm.reportPerson;
    data.reportPersonNa = IsEmpty(detailForm.testDoctorNa) ? null : detailForm.testDoctorNa;
    data.requestNo = IsEmpty(detailForm.requestNo) ? null : detailForm.requestNo;
    data.remark = IsEmpty(detailForm.remark) ? null : detailForm.remark;
    data.reportTime = IsEmpty(detailForm.reportTime) ? null : detailForm.reportTime;
    data.itemNo = IsEmpty(item.itemNo) ? null : item.itemNo;
    data.patNo = IsEmpty(mainInfo.patNo) ? null : mainInfo.patNo;
    data.currentResult = IsEmpty(item.alarmText) ? null : item.alarmText;
    data.reTestResult = IsEmpty(item.reTestResult) ? null : item.reTestResult;
    data.isReTest = IsEmpty(detailForm.isReTest) ? null : detailForm.isReTest;
    data.notificationType = IsEmpty(detailForm.notificationType) ? null : detailForm.notificationType;
    data.notificationTypeNa = tzfs;
    data.criticalType = 2;
    data.criticalItemType = item.criticalItemType;
    saveData.push(data);
    logData.push({ criData: data, criItem: item });
  });

  const url = '/lab/criticalReport/batchAddCriticalReportList';
  proxy.$http
    .post(url, saveData)
    .then((res: any) => {
      getAlarmResultData(() => {
        if (wlResultList && wlResultList.length <= 0) {
          detailModalShow.value = false;
        }
      }); // 获取是危急值的结果信息
      if (res && res.status && !IsEmpty(res.status.code) && res.status.code === 1) {
        //findBacDrugTestResult(curTestResultObj);
        VxeMessage(res.status.msg, VxeNotifyType.success);
        proxy.$emit('treatFinish', logData);
      } else {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}
// 点击组件表格行(被通知人)
function SelectRowClick1(row) {
  detailForm.notifyPerson = row.row.code;
  detailForm.reqDoctorNa = row.row.name;
}
// 点击组件表格行(上报人员)
function SelectRowClick(row) {
  detailForm.reportPerson = row.row.username;
  detailForm.testDoctorNa = row.row.realname;
}

// 清空组件输入框(被通知人)
function clearValueHandler1() {
  detailForm.notifyPerson = '';
}
// 清空组件输入框(上报人员)
function clearValueHandler() {
  detailForm.reportPerson = '';
}

// 键盘事件删除输入框文字(被通知人)
function sliceHandler1() {
  let newStr = detailForm.notifyPerson.slice(0, -1);
  detailForm.notifyPerson = newStr;
}

// 键盘事件删除输入框文字(上报人员)
function sliceHandler() {
  let newStr = detailForm.reportPerson.slice(0, -1);
  detailForm.reportPerson = newStr;
}

//获取处理措施数据字典
function getDictMeasureList() {
  measureList.length = 0;
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    .get(url, { params: { code: 'measure' } })
    .then((res: any) => {
      measureList.push(...res.data);
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}
/**危急值通知方式 */
function getDictCriNotificationTypeList() {
  criNotoficationTypeList.length = 0;
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    .get(url, { params: { code: 'CriNotificationType' } })
    .then((res: any) => {
      criNotoficationTypeList.push(...res.data);
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}
//获取病人类型数据字典
function getDictPatTypeList() {
  patTypeList.length = 0;
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    .get(url, { params: { code: 'PATTYPE' } })
    .then((res: any) => {
      patTypeList.push(...res.data);
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}
function getDictDetailList() {
  resultflags.length = 0;
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    .get(url, { params: { code: 'resultFlag' } })
    .then((res: any) => {
      resultflags.push(...res.data);
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}
/**判断是否审核，若审核范围ture */
function resultIsDisabled() {
  if (!IsEmpty(mainInfo) && mainInfo.isChk == '2') {
    return true;
  } else {
    return false;
  }
}
</script>

<style lang="scss" scoped>
:deep(.vxe-modal--wrapper) {
  z-index: 10 !important;
}
:deep(.el-descriptions__label) {
  width: 120px;
}
:deep(.el-descriptions__content) {
  width: 400px;
  color: #000;
}
:deep(.vxe-cell) {
  padding-left: 5px;
}
.tableForm {
  height: calc(100% - 80px);
  .tableBody {
    height: 75%;
  }
  .formBody {
    height: 25%;
    padding: 0 25px;
    :deep(.vxe-form--item) {
      margin-right: 15px;
    }
  }
}
</style>
<style lang="scss" scoped>
.criticalValueResultForm.vxe-form {
  .vxe-switch {
    padding: 0;
  }
}

.form-panel {
  :deep(.vxe-input--inner) {
    border-radius: 4px !important;
  }
}
</style>
